#include <Button.h>

Button::Button(uint8_t pin, cb_func short_press_func, cb_func long_press_func) {
    this->pin = pin;
    this->short_press_func = short_press_func;
    this->long_press_func = long_press_func;
    this->interval = UINT32_MAX;
    this->cur_key_state = KeyState::IDLE;
    this->press_time = 0;
    this->pre_millis = 0;
}

void Button::begin(uint32_t interval) {
    this->interval = interval;
    pinMode(pin, INPUT_PULLUP);
}

bool Button::is_pressed() {
    return digitalRead(pin) ^ 1;
}


Button::KeyState Button::get_key_state() {
    return cur_key_state;
}


void Button::run() {
    const uint32_t cur_millis = millis();
    if (cur_millis - pre_millis < interval) return ;
    pre_millis = cur_millis;

    press_time = is_pressed() ? press_time + interval : 0;

    if (press_time < short_press_time) {

        cur_key_state = KeyState::IDLE;

    } else if (press_time >= short_press_time && press_time < long_press_time) {

        if (cur_key_state != KeyState::IDLE) return ;

        cur_key_state = KeyState::SHORT_PRESS;
        short_press_func();

    } else if (press_time >= long_press_time) {

        if (cur_key_state == KeyState::LONG_PRESS) return ;

        cur_key_state = KeyState::LONG_PRESS;
        long_press_func();

    }
}